<template>
  <div class="process app-container" ref="process" :style="{ 'max-width': processWidth + 'px' }">
    <a-tabs v-model:active-key="searchObj.portraitId" @change="changeTabs">
      <a-tab-pane v-for="item in portraitTabs" :key="item.portraitId" :title="item.portraitName"></a-tab-pane>
    </a-tabs>
    <div class="head" v-if="portraitTabs.length">
      <a-space>
        <a-button type="primary" @click="openStageVisible">
          <template #icon>
            <icon-plus />
          </template>
          添加工程阶段
        </a-button>
        <a-button type="outline" @click="handelSetAccept">
          <template #icon>
            <icon-settings />
          </template>
          设置验收人
        </a-button>
      </a-space>
      <div class="switch">
        是否展示禁用任务
        <a-switch size="small" v-model="searchObj.showStatus" :unchecked-value="0" :checked-value="1" @change="init" />
      </div>
    </div>
    <div class="process__table" v-if="tableData.length">
      <div class="table-head">
        <div v-for="item in columns" :key="item.dataIndex">{{ item.title }}</div>
      </div>
      <div class="process__table__body">
        <div
          :class="{ 'table-item': true, 'table-head': item.templateTaskList?.length == 0 }"
          v-for="item in tableData"
          :key="item.stageSettingId"
        >
          <div class="table-title">
            <div>{{ item.stageName }}</div>
            <div class="right">
              <div v-if="!item.templateTaskList || item.templateTaskList?.length == 0" @click="delCustomerStage(item, 'stage')">
                删除
              </div>
              <div v-else-if="!unfoldArr.includes(item.stageSettingId)" @click="unfold(item.stageSettingId)">
                展开更多({{ item.templateTaskList ? item.templateTaskList.length : 0 }})
                <icon-down />
              </div>
              <div v-else-if="unfoldArr.includes(item.stageSettingId)" @click="collapse(item.stageSettingId)">
                收起
                <icon-up />
              </div>
            </div>
          </div>
          <template v-if="unfoldArr.includes(item.stageSettingId)">
            <div class="item-item_row" v-for="record in item.templateTaskList || []">
              <template v-for="key in columns">
                <div v-if="key.dataIndex">{{ record[key.dataIndex] }}</div>
                <div v-if="key.slotName == 'status'">
                  <a-switch v-model="record.status" :unchecked-value="0" :checked-value="1" @change="updateStatus(record)" />
                </div>
                <div v-if="key.slotName == 'isMust'">
                  {{ record.isMust == 1 ? "是" : "否" }}
                </div>
                <div v-if="key.slotName == 'operate'">
                  <a-button type="text" size="mini" @click="handelEditFlowTask(item, record)">编辑</a-button>
                  <a-button type="text" size="mini" @click="handleReferenceData(record)">参考数据</a-button>
                  <a-button type="text" size="mini" @click="delCustomerStage(record, 'task')">删除</a-button>
                </div>
              </template>
            </div>
            <div class="add">
              <span @click="handelAddFlowTask(item)"><icon-plus /> 添加任务</span>
            </div>
          </template>
        </div>
      </div>
    </div>
    <div class="empty" v-else>
      <img src="@/assets/images/empty.png" alt="" />
      <div>这里什么都没有{{ !portraitTabs.length ? "，请先配置客户画像" : "" }}</div>
    </div>
  </div>
  <!--  start 删除-->
  <delDialog
    v-if="showDelDialog"
    :currentTaskSettingId="currentTaskSettingId"
    :currentPortraitId="searchObj.portraitId"
    :stageSettingId="stageDetail.stageSettingId"
    :currentDeleteType="currentDeleteType"
    @handleDelete="handleDelete"
  >
  </delDialog>
  <!--  end 删除-->
  <!-- start 新增阶段 -->
  <addStage
    v-model="showAddStageDialog"
    v-if="showAddStageDialog"
    :portraitId="searchObj.portraitId"
    :portraitName="currentPortraitName"
    @getPortrait="getPortrait"
  >
  </addStage>
  <!--  end 新增阶段-->
  <!--  start 新增任务-->
  <addTask
    v-if="showAddTaskDialog"
    :taskEditType="taskEditType"
    :rules="[required]"
    :stageDetail="stageDetail"
    :currentTaskSettingId="currentTaskSettingId"
    :currentStageType="currentStageType"
    :currentPortraitId="searchObj.portraitId"
    @handleTask="handleTask"
  ></addTask>
  <!--  end 新增任务-->
  <referenceData v-if="showReferenceDialog" :task-setting-id="taskSettingId" @handleReferenceClose="handleReferenceClose">
  </referenceData>
</template>

<script setup lang="ts">
import { businessType, setTaskStatus } from "@/apis/system";
import type { ProcessParams, ProcessListItem, CustomerProfilingItem, ProcessTaskItem } from "@/apis/system/type";
import delDialog from "./components/deleteDialog.vue";
import addStage from "./components/addStageDialog.vue";
import addTask from "./components/addTaskDialog.vue";
import referenceData from "../referenceDataDialog/index.vue";
import { Message } from "@arco-design/web-vue";
import { required } from "../../config";
import { getBuildStageTaskList } from "@/apis/engineeringSettings/process";
import { useUserStore } from "@/stores";

const props = defineProps(["width"]);
const emit = defineEmits(["openFlow"]);

const userStore = useUserStore();

const processWidth = computed(() => props.width - 14);
const process = ref();
//业务类型tab模块
const portraitTabs = ref<CustomerProfilingItem[]>([]);
/**
 * 获取业务类型-原客户画像
 */
const searchObj = ref<ProcessParams>({
  portraitId: "",
  showStatus: 0
});
const currentPortraitName = ref("");
const getPortrait = async () => {
  const res = await businessType();
  portraitTabs.value = res.data || [];
  searchObj.value.portraitId = searchObj.value.portraitId == "" ? (res.data[0].portraitId as string) : searchObj.value.portraitId;
  changeTabs();
};
const changeTabs = () => {
  currentPortraitName.value = portraitTabs.value.find(item => item.portraitId == searchObj.value.portraitId)
    ?.portraitName as string;
  init();
};
//表格模块
const unfoldArr = ref<any[]>([]);
const columns = [
  { title: "排序号", dataIndex: "orderNum", width: 100 },
  { title: "任务名称", dataIndex: "taskName", width: 100 },
  { title: "责任人", dataIndex: "roleName", width: 150 },
  { title: "标准天数", dataIndex: "executeDays" },
  { title: "间隔天数", dataIndex: "intervalDays" },
  { title: "状态", slotName: "status", width: 100 },
  { title: "前置流程", dataIndex: "beforeTaskNames", width: 100 },
  { title: "验收项", dataIndex: "checkName" },
  { title: "操作", slotName: "operate", width: 200 }
];
const tableData = ref<any[]>([]);
const init = async () => {
  const { portraitId, showStatus } = searchObj.value;
  const res = await getBuildStageTaskList(portraitId, { status: showStatus == 0 ? 1 : 0 });
  tableData.value = res.data || [];
  unfoldArr.value = tableData.value.map(v => v.stageSettingId);
};
/**
 * 展开表格
 * @param id 展开表格key
 */
const unfold = (id: string) => {
  unfoldArr.value.push(id);
};
/**
 * 收起表格
 * @param id 收起的表格key
 */
const collapse = (id: string) => {
  unfoldArr.value.splice(unfoldArr.value.indexOf(id), 1);
};
const updateStatus = async (item: ProcessTaskItem) => {
  try {
    await setTaskStatus(item.taskSettingId as string, item.status);
    Message.success("操作成功");
    init();
  } catch (err) {
    item.status = item.status == 1 ? 0 : 1;
  }
};

/**
 * 设置验收流程
 */
const handelSetAccept = () => {
  const formId = `form-acceptance-${userStore.userInfo?.tenantId}`;
  const data = { params: { formId } };
  emit("openFlow", data);
};

//阶段模块
const showAddStageDialog = ref(false);
const openStageVisible = () => {
  showAddStageDialog.value = true;
};
const handleAddStage = (type: string) => {
  showAddStageDialog.value = false;
  if (type == "confirm") {
    init();
  }
};

//任务模块
//删除任务
const showDelDialog = ref(false);
const currentDeleteType = ref("");
const delCustomerStage = async (item: any, type: string) => {
  currentDeleteType.value = type;
  if (type == "task") {
    currentTaskSettingId.value = item.taskSettingId;
  }
  if (type == "stage") {
    stageDetail.value = { stageName: item.stageName, stageSettingId: item.stageSettingId };
  }
  showDelDialog.value = true;
};
const handleDelete = (type: string) => {
  showDelDialog.value = false;
  if (type == "confirm") {
    init();
  }
};
//新增任务
const taskEditType = ref("add");
const showAddTaskDialog = ref(false);
const currentTaskSettingId = ref("");
const currentStageType = ref("");
const handelAddFlowTask = (stage: ProcessListItem) => {
  taskEditType.value = "add";
  showAddTaskDialog.value = true;
  currentStageType.value = stage.stageType;
  // stageDetail.value = {stageName: '测试',stageSettingId:'1'}
  stageDetail.value = { stageName: stage.stageName, stageSettingId: stage.stageSettingId };
};
const handelEditFlowTask = async (stage: ProcessListItem, process: ProcessTaskItem) => {
  if (!process || !process.taskSettingId) {
    return Message.error("请选择要编辑的任务");
  }
  currentTaskSettingId.value = process.taskSettingId;
  currentStageType.value = stage.stageType;
  taskEditType.value = "edit";
  stageDetail.value = { stageName: stage.stageName, stageSettingId: stage.stageSettingId };
  showAddTaskDialog.value = true;
};

// 任务详情--阶段名称
const stageDetail = ref({
  stageName: "",
  stageSettingId: ""
});
const handleTask = () => {
  showAddTaskDialog.value = false;
  init();
};
/**
 * 参考数据
 */
const showReferenceDialog = ref(false);
const taskSettingId = ref("");
const handleReferenceData = (record: any) => {
  showReferenceDialog.value = true;
  taskSettingId.value = record.taskSettingId;
};
const handleReferenceClose = () => {
  showReferenceDialog.value = false;
};

onMounted(() => {
  // console.log("mount")
  getPortrait();
});
</script>

<style scoped lang="scss">
@import "index";
</style>
